<template>
	<div>
		<div class="crumbs">
			<el-breadcrumb separator="/">
				<el-breadcrumb-item>
					<i class="el-icon-lx-warn"></i> 权限设置 / 角色列表
				</el-breadcrumb-item>
			</el-breadcrumb>
		</div>
		<div class="container">
			<div class="handle-box">
				<el-button type="primary" icon="el-icon-lx-add" @click="handleAdd" size="small">添加</el-button>
				<el-button icon="el-icon-lx-refresh" @click="refreshPage" :loading="refreshLoading" size="small">刷新</el-button>
			</div>
			<el-table :data="tableData" border class="table" ref="multipleTable" header-cell-class-name="table-header">
				<el-table-column prop="id" label="ID" width="55" align="center"></el-table-column>
				<el-table-column prop="title" label="角色" align="center" width="180"></el-table-column>
				<el-table-column prop="desc" label="备注" align="center"></el-table-column>
				<el-table-column label="状态" align="center" width="120">
					<template #default="scope">
						<el-tag :type="scope.row.status === 1 ? 'success' :  'danger'">
							{{ scope.row.status === 1 ? '正常' : '停用' }}
						</el-tag>
					</template>
				</el-table-column>
				<el-table-column label="操作" min-width="180" align="center">
					<template #default="scope">
						<el-button type="text" icon="el-icon-edit" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
						<el-button type="text" icon="el-icon-edit" @click="handleConfig(scope.$index, scope.row)">路由权限</el-button>
						<el-button type="text" icon="el-icon-delete" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
					</template>
				</el-table-column>
			</el-table>
		</div>
		<el-dialog  title="添加角色" v-model="addVisible" custom-class="dialog-page">
			<el-form :model="formData" :rules="rules" label-width="100px" ref="formAdd">
				<el-form-item prop="title" label="角色名称">
					<el-input v-model="formData.title" maxlength="30" show-word-limit class="short-input" placeholder="请输入名称"></el-input>
				</el-form-item>
				<el-form-item prop="desc" label="角色备注">
					<el-input v-model.trim="formData.desc" maxlength="100" show-word-limit placeholder="请填写备注"></el-input>
				</el-form-item>
				<el-form-item prop="rules" label="配置权限">
					<template v-for="(item,index) in nodeList" :key="item.id">
						<el-transfer v-if="item.data.length > 0" :titles="item.titles" v-model="item.value" :data="item.data" />
					</template>
				</el-form-item>
				<el-form-item label="状态" prop="status">
					<el-radio-group v-model="formData.status">
						<el-radio label="1">正常</el-radio>
						<el-radio label="0">已停用</el-radio>
					</el-radio-group>
				</el-form-item>
			</el-form>
			<template #footer>
                <span class="dialog-footer">
                    <el-button @click="addVisible=false">取 消</el-button>
                    <el-button type="primary" @click="addSubmit">添 加</el-button>
                </span>
			</template>
		</el-dialog>
		<el-dialog  title="编辑角色" v-model="editVisible" custom-class="dialog-page">
			<el-form :model="formData" :rules="rules" label-width="100px" ref="formEdit">
				<el-form-item prop="title" label="角色名称">
					<el-input v-model="formData.title" maxlength="30" show-word-limit class="short-input" placeholder="请输入名称"></el-input>
				</el-form-item>
				<el-form-item prop="desc" label="角色备注">
					<el-input v-model.trim="formData.desc" maxlength="100" show-word-limit placeholder="请填写备注"></el-input>
				</el-form-item>
				<el-form-item prop="rules" label="配置权限">
					<template v-for="(item,index) in nodeList" :key="item.id">
						<el-transfer v-if="item.data.length > 0" :titles="item.titles" v-model="item.value" :data="item.data" />
					</template>
				</el-form-item>
				<el-form-item label="状态" prop="status">
					<el-radio-group v-model="formData.status">
						<el-radio label="1">正常</el-radio>
						<el-radio label="0">已停用</el-radio>
					</el-radio-group>
				</el-form-item>
			</el-form>
			<template #footer>
                <span class="dialog-footer">
                    <el-button @click="editVisible=false">取 消</el-button>
                    <el-button type="primary" @click="saveSubmit">保 存</el-button>
                </span>
			</template>
		</el-dialog>
		<el-dialog  title="路由权限" v-model="routeVisible" custom-class="dialog-page">
			<el-form :rules="rules" label-width="100px">
				<el-form-item prop="rules" label="配置权限">
					<template v-for="(item,index) in routeList" :key="item.id">
						<el-transfer :titles="item.titles" v-model="item.value" :data="item.data" />
					</template>
				</el-form-item>
			</el-form>
			<template #footer>
          <span class="dialog-footer">
              <el-button @click="routeVisible=false">取 消</el-button>
              <el-button type="primary" @click="routeSubmit">保 存</el-button>
          </span>
			</template>
		</el-dialog>
	</div>
</template>
<script>
import { ref, reactive,toRaw, defineComponent } from "vue";
export default defineComponent({name:'rolelist'})
</script>
<script setup>
import { ElMessage, ElMessageBox } from "element-plus";
import {
	getRoleList,
	roleDetail,
	roleAdd,
	roleDelete,
	roleMod,
	getNodeList,
	roleRouteMod
} from "../../api/api";
import { ElLoading } from 'element-plus';
import Methods from "../../utils/Methods";
const query = reactive({
	pageIndex: 1,
	pageSize: 10,
})
const tableData = ref([])
const nodeList = ref([])
const routeList = ref([])
const addVisible = ref(false);
const editVisible = ref(false);
const routeVisible = ref(false);
const formAdd = ref(null)
const formEdit = ref(null)
const formData = reactive({
	title: "",
	desc: "",
	status: "1"
})

let loading = null
let editId = ''
const loadingStart = () => {
	loading = ElLoading.service({
		lock: true,
		text: 'Loading',
		spinner: 'el-icon-loading',
		background: 'rgba(0, 0, 0, 0.3)',
	})
}
const getData = () => {
	query.token = Methods.getLocalStorage('admin_token')
	getRoleList(query).then(res => {
		tableData.value = res.list
	}).catch(err => {
		console.log(err,'----errr')
	})
}
let list = []
let myNode = []
let myRoute = []
const nodeListInit = (list) => {
	let plist = []
	for(let index in list) {
		if(list[index].pid === 0) {
			plist.push(list[index])
		}
	}
	for(let index in plist) {
		let data = []
		let value = []
		let titles = [plist[index].title,'已拥有']
		for(let cindex in list) {
			if(plist[index].id === list[cindex].pid) {
				data.push({
					key:list[cindex].id,
					label:list[cindex].title,
				})
				if(myNode.indexOf(list[cindex].id.toString()) !== -1) {
					value.push(list[cindex].id)
				}
			}
		}
		plist[index].data = data
		plist[index].value = value
		plist[index].titles = titles
	}
	nodeList.value = plist
}
const getNodeData = () => {
	getNodeList(query).then(res => {
    console.log("getNodeData", res)
		list = res
		nodeListInit(list)
	}).catch(err => {console.log(err)})
}
getData()
getNodeData()
const refreshLoading = ref(false)
const refreshPage = () => {
	refreshLoading.value = true
	Promise.all([getData(), getNodeData()]).then(res => {
		ElMessage.success('已刷新')
		refreshLoading.value = false
	}).catch(err => {console.log(err)})
}
//删除操作
const handleDelete = (index) => {
	ElMessageBox.confirm("确定要删除吗？", "提示", {
		type: "warning",
	}).then(() => {
		let data = {
			id: tableData.value[index].id,
			token: Methods.getLocalStorage('admin_token')
		}
		return roleDelete(data)
	}).then(res => {
		ElMessage.success("已删除")
		tableData.value.splice(index,1)
	}).catch(err => {
		console.log(err,'----unblock err')
	})
}
//增
const handleAdd = () => {
	formData.title = ""
	formData.desc = ""
	formData.status = "1"
	myNode = []
	nodeListInit(list)
	addVisible.value = true
}
//配置路由
const handleConfig = (index,row) => {
	editId = row.id
	routeVisible.value = true
	let query = { id: editId, token: Methods.getLocalStorage('admin_token') }
	roleDetail(query).then(res => {
		if(res.route) {
			myRoute = res.route.split(',')
		}else {
			myRoute = []
		}
		let list = res.menu_list
		let plist = []
		for(let index in list) {
			if(list[index].pid === 0) {
				plist.push(list[index])
			}
		}
		for(let pindex in plist) {
			let data = []
			let value = []
			data.push({
				key:plist[pindex].id,
				label:plist[pindex].title,
			})
			if(myRoute.indexOf(plist[pindex].id.toString()) !== -1) {
				value.push(plist[pindex].id)
			}
			let titles = [plist[pindex].title,'已拥有']
			for(let index in list) {
				if(list[index].pid === plist[pindex].id) {
					data.push({
						key:list[index].id,
						label:list[index].title,
					})
					if(myRoute.indexOf(list[index].id.toString()) !== -1) {
						value.push(list[index].id)
					}
				}
			}
			plist[pindex].data = data
			plist[pindex].value = value
			plist[pindex].titles = titles
		}
		routeList.value = plist
	}).catch(err => {console.log(err)})
}
//改
const handleEdit = (index,row) => {
	editVisible.value = true
	editId = row.id
	let query = { id: editId, token: Methods.getLocalStorage('admin_token') }
	roleDetail(query).then(res => {
		myNode = res.rules.split(',')
		formData.title = res.title
		formData.desc = res.desc
		formData.status = res.status.toString()
		nodeListInit(list)
	}).catch(err => {console.log(err)})
}

const rules = {
	title: [{required: true, message: "请输入角色名称", trigger: "blur",},],
};
const addSubmit = () => {
	formAdd.value.validate((valid) => {
		if (valid) {
			let data = toRaw(formData)
			data.token = Methods.getLocalStorage('admin_token')
			let rules = []
			for(let index in nodeList.value) {
				if(nodeList.value[index].value.length > 0) {
					rules = rules.concat(nodeList.value[index].value)
				}
			}
			data.rules = rules
			loadingStart()
			roleAdd(data).then(res => {
				ElMessage.success("添加成功")
				addVisible.value = false
				loading.close()
				getData()
			}).catch(err => {
				console.log(err)
				loading.close()
			})
		} else {
			return false
		}
	})
}
const saveSubmit = () => {
	formEdit.value.validate((valid) => {
		if (valid) {
			let data = toRaw(formData)
			data.id = editId
			data.token = Methods.getLocalStorage('admin_token')
			let rules = []
			for(let index in nodeList.value) {
				if(nodeList.value[index].value.length > 0) {
					rules = rules.concat(nodeList.value[index].value)
				}
			}
			data.rules = rules
			loadingStart()
			roleMod(data).then(res => {
				ElMessage.success("保存成功")
				editVisible.value = false
				loading.close()
				getData()
			}).catch(err => {
				loading.close()
			})
		} else {
			return false
		}
	})
}
const routeSubmit = () => {
	let data = {}
	data.id = editId
	data.token = Methods.getLocalStorage('admin_token')
	let route = []
	for(let index in routeList.value) {
		if(routeList.value[index].value.length > 0) {
			route = route.concat(routeList.value[index].value)
		}
	}
	data.route = route
	loadingStart()
	roleRouteMod(data).then(res => {
		ElMessage.success("保存成功")
		routeVisible.value = false
		loading.close()
	}).catch(err => {
		loading.close()
	})
}
</script>

<style scoped lang="scss">
.handle-box {
	margin-bottom: 5px;
	//display: flex;
	//flex-wrap: wrap;
}
.handle-select {
	width: 150px;
	margin-bottom: 15px;
}
.handle-input {
	width: 300px;
	margin-bottom: 15px;
}
.table {
	width: 100%;
	font-size: 14px;
	.cover {
		width: 50px;
		height: 50px;
		border-radius: 3px;
		background-position: center center;
		background-size: cover;
	}
}
.red {
	color: #ff0000;
}
.mr10 {
	margin-right: 10px;
}
::v-deep(.dialog-page) {
	max-width: 1200px;
	min-width: 800px;
}
.short-input {
	width: 400px;
}

</style>
